package TreeStructure;

import java.io.File;
import java.io.IOException;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class DOMParser {
	private Document doc = null;
	private Tree<MyNode> tree = new Tree<MyNode>();
	private TreeNode<MyNode> root = new TreeNode<MyNode>();
	private TreeNode<MyNode> auxTreeNode = new TreeNode<MyNode>();

	public DOMParser() {
		try {
			doc = parserXML(new File("D:/Workplace/Atrium/src/TreeStructure/file.xml"));
			MyNode mn = new MyNode();
			mn.setName("root");
			mn.setLinkReal("#");
			mn.setLink("#");
			root = tree.AddNode(mn, null);
			visit(root, doc, 0);
		} catch (Exception error) {
			error.printStackTrace();
		}
	}

	public void visit(TreeNode<MyNode> parentTreeNode, Node node, int level) {
		NodeList nl = node.getChildNodes();

		for (int i = 0, cnt = nl.getLength(); i < cnt; i++) {
			if (!nl.item(i).getNodeName().equals("#text") && !nl.item(i).getNodeName().equals("root")) {
				// System.out.println(nl.item(i).getAttributes().item(2) +
				// " Level:" + level);
				MyNode mn = new MyNode();
				mn.setName(nl.item(i).getAttributes().item(0).getTextContent());
				mn.setLink(nl.item(i).getAttributes().item(1).getTextContent());
				mn.setLinkReal(nl.item(i).getAttributes().item(2).getTextContent());
				auxTreeNode = tree.AddNode(mn, parentTreeNode);
				visit(auxTreeNode, nl.item(i), level + 1);
			}
			else{
				visit(parentTreeNode, nl.item(i), level + 1);
			}
		}
	}

	public Tree<MyNode> getTree() {
		return tree;
	}

	public void setTree(Tree<MyNode> tree) {
		this.tree = tree;
	}

	public Document parserXML(File file) throws SAXException, IOException, ParserConfigurationException {
		return DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(file);
	}
}
